package com.xxxx.yoyo.adminweb;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Admin;
import com.xxxx.yoyo.service.IAdminService;
import com.xxxx.yoyo.service.impl.AdminServiceImpl;

/**
 * 管理员登录界面，查询账号密码是否正确
 * Servlet implementation class LoginServlet
 */
@WebServlet(name = "AdminLoginServlet", urlPatterns = { "/admin/login" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IAdminService adminService = new AdminServiceImpl();
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式为UTF-8,---解决中文乱码
		request.setCharacterEncoding ("UTF-8");
		
		//获取前端页面传递的参数username,password
		String username = request.getParameter("username");
		String password = request.getParameter("password");//明文密码
		
		//根据用户名和密码查询用户
		Admin admin = adminService.getAdminByUsernameAndPassword (username, password);
		if(admin == null){//没查到----用户名或者密码错误
			//提示错误
			request.setAttribute("msg","登录失败！用户名或者密码错误！");
			//请求转发，跳转到/admin/login.jsp页面
			request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
		}else {//查到了 ---登录成功
			//获取session
			HttpSession session = request.getSession();
			//把管理员存入sess1on,方便其他地方使用.
			session.setAttribute ("admin",admin);
			
			
			//请求转发，跳转到后台首页 /admin/index.jsp
			request.getRequestDispatcher("/admin/index.jsp").forward(request,response);
			
		}
		
		
	}

}
